#include "qPLTMlista.h"
#include <QSqlQuery>
#include <QSqlRecord>
#include "chelperclass.h"
#include <QDesktopWidget>
#include <QSplitter>




QPLTMLista::QPLTMLista(QWidget *parent)
	: QMyBaseFormWidget(parent)
	,m_row(0)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();

	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
	ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.tableView_2->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.tableView_2->setSelectionBehavior(QAbstractItemView::SelectRows);
    //connect(ui.lineEdit_7, SIGNAL(textChanged(const QString &)), this, SLOT(lineEdit7Pressed(const QString &)));


	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));
	ui.tableView_2->setSortingEnabled(true);
	connect(ui.tableView_2->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView_2, SLOT(sortByColumn(int)));
	createProdavnicaList();
    m_selectedText = model->item(0, 0) ? model->item(0, 0)->text():"";
    lista_detail(m_selectedText);
	//ui.tableView->setSortingEnabled(true); 
	connect(ui.comboBox, SIGNAL(currentIndexChanged(const QString &)),this, SLOT(procComboBoxChanged(const QString &)));

	ui.tableView->setFocus();
}

void QPLTMLista::procComboBoxChanged(const QString & text)
{
	int stop = 0;
	QStringList mailids = text.split("-");
	lista(mailids.at(0));
}

void QPLTMLista::createProdavnicaList()
{
	QString temp = 
		"select distinct komintenti.id, komintenti.naziv "
		"from dokumenti_prodavnica  "
		"left join komintenti on dokumenti_prodavnica.prodavnica_id = komintenti.id "
		"where dok_tip = 20 ";
	QSqlQuery query(temp);
	ui.comboBox->addItem("");
	while (query.next()) 
	{
		ui.comboBox->addItem(query.value(0).toString() + "-" + query.value(1).toString());
	}
	lista("");
}


QPLTMLista::~QPLTMLista()
{

}

void QPLTMLista::setRow(int mrow)
{
	ui.tableView->selectRow(mrow);
}

int QPLTMLista::getRow()
{
	return m_row;
}

void QPLTMLista::pressEscape()
{
    emit closeW();
}

void QPLTMLista::pressReturn()
{
	if (ui.tableView->hasFocus())
	{
		//emit sFakturiToIzvod(ui.lineEdit_6->text(), ui.lineEdit_8->text(), ui.lineEdit_9->text(), m_selectedText);	
	}
}
void QPLTMLista::lista(const QString& nameSearch)
{
    QLocale loc;
    if (nameSearch.length() < 0)
    {
        ui.tableView->hide();
        return;
    }
    int r = 0;
    int c = 5;
    int fieldNo[10];
    QString country[10];
    int colWidth[] = {0, 0, 80, 300, 120,120,120, 0, 0, 80};
    QString colName[] = {"id", "dok_id", "datum", "naziv", "adresa", "grad"};
	QString tempA = "";
	if(nameSearch != "")
	{
		tempA = " and prodavnica_id = " + nameSearch; 
	}

	QString temp = 
        " select dokumenti_prodavnica.id, dok_id, datum, komintenti.naziv, dok_id_prodavnica "
        " from dokumenti_prodavnica "
        " left join komintenti on dokumenti_prodavnica.komintent_id = komintenti.id "
        " where dok_tip = 20 "
		+ tempA +
		" order by dok_id desc "
        ;
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Id."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Ид.."));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Датум"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Коминтенти"));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("ПЛТМ бр"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
	CHelperClass chc(this);
	QString tip = "40";

    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = new QStandardItem(query.value(i).toString());
            if ((i == 1))
            {
                item->setTextAlignment(Qt::AlignLeft);
            }

            if ((i == 2))
            {

                item = new QStandardItem(query.value(i).toString().left(10));
                item->setTextAlignment(Qt::AlignLeft);
            }

            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            item->setEditable(false);
            model->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
}
void QPLTMLista::selectionChanged(QModelIndex modelX, QModelIndex modelY)
{
    int i = modelX.row();
	m_row = modelX.row();;
    m_selectedText = model->item(i, 1) ? model->item(i, 1)->text():"";

    m_fakturaBr = model->item(i, 1)->text();
    m_fakturadatum = model->item(i, 2)->text();
    m_komintent_naziv =  model->item(i, 3)->text();
	m_pltm_broj_print = model->item(i, 4)->text();
	showProdavnicaInfo(m_selectedText);
    lista_detail(m_selectedText);
}

void QPLTMLista::showProdavnicaInfo(const QString& nameSearch)
{
	QLocale loc;
	if (nameSearch.length() < 0)
	{
		ui.tableView->hide();
		return;
	}
	QString temp = 
		" SELECT komintenti.naziv, komintenti.adresa, komintenti.grad, komintenti.edb, komintenti.zirosmetka "
		" FROM dokumenti_prodavnica "
		" LEFT JOIN komintenti ON dokumenti_prodavnica.prodavnica_id = komintenti.id "
		" WHERE dok_tip = 20 AND dok_id = "+ nameSearch;
	QSqlQuery query(temp);
	while (query.next()) 
	{
		ui.lineEdit->setText(query.value(0).toString());
		ui.lineEdit_2->setText(query.value(1).toString());
		ui.lineEdit_3->setText(query.value(2).toString());
		ui.lineEdit_4->setText(query.value(3).toString());
		ui.lineEdit_5->setText(query.value(4).toString());
	} 
}

void QPLTMLista::lista_detail(const QString& nameSearch)
{
    QLocale loc;
    if (nameSearch.length() < 0)
    {
        ui.tableView_2->hide();
        return;
    }

    int r = 0;
    int c = 11;
    int fieldNo[11];
    QString country[11];
    int colWidth[] = {80, 270, 70, 70, 70, 70, 70, 100, 70, 100, 100};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "rabat" "iznos", "ddv", "iznosddv", "vkupeniznos"};
    QString temp = 
        "select "
		"artikli.id, "
		"artikal, "
		"edm, "
		"kol, "
		"edinecna_nabavna_cena ," 
		"iznos_nabavna, " 
		"ddv_nabavna, " 
		"stapka_ddv, " 
		"edinecna_prodazna_cena, " 
		"iznos_prodazna, " 
		"vk_ddv_prodazna " 
		"from magacin_prodavnica "
        "left join artikli on magacin_prodavnica.artikal_id = artikli.id "
        "where magacin_prodavnica.dok_tip = 20 and magacin_prodavnica.dok_id=       ";
    temp += m_selectedText;
    temp += "";
    QSqlQuery query(temp);

	model2 = new QStandardItemModel(r,c);
	
	model2->setHeaderData( 0, Qt::Horizontal, trUtf8("1\nШифра."));
	model2->setHeaderData( 1, Qt::Horizontal, trUtf8("2\nНазив на\nСтоките"));
	model2->setHeaderData( 2, Qt::Horizontal, trUtf8("3\nЕдинечна мера"));
	model2->setHeaderData( 3, Qt::Horizontal, trUtf8("4\nКол"));
	model2->setHeaderData( 4, Qt::Horizontal, trUtf8("5\nЕдин.Цена"));
	model2->setHeaderData( 5, Qt::Horizontal, trUtf8("6\nИзнос(4х5)"));
	model2->setHeaderData( 6, Qt::Horizontal, trUtf8("7\nДДВ при\nНабавка"));
	model2->setHeaderData( 7, Qt::Horizontal, trUtf8("8\nПропишана\nстапка ДДВ"));
	model2->setHeaderData( 8, Qt::Horizontal, trUtf8("9\nЕдин.Цена"));
	model2->setHeaderData( 9, Qt::Horizontal, trUtf8("10\nИзнос(4х9)"));
	model2->setHeaderData( 10, Qt::Horizontal, trUtf8("11\nВкупен ДДВ\nво прод. вредн"));

	ui.tableView_2->setModel(model2);
    header2 = new QHeaderView(Qt::Horizontal, this);
	header2->setClickable(true);
    ui.tableView_2->setHorizontalHeader(header2);
    header2->show();
    int row = 0;
    float sumaDDV = 0.f;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            fieldNo[i] = i; //query.record().indexOf(colName[i]);
            QStandardItem *item = NULL;
            QString temp = query.value(fieldNo[i]).toString();
            if (i > 2)
            {
                item = new QStandardItem(loc.toString(temp.toFloat(), 'f', 2));
                item->setTextAlignment(Qt::AlignRight);
                if (i == 10)
                {
                    sumaDDV += temp.toFloat();
                }
            }
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }
            
            item->setEditable(false);
            ui.tableView_2->setRowHeight(row, 18);
            ui.tableView_2->setColumnWidth(i, colWidth[i]);
            model2->setItem(row, i, item);
        }
        row++;
    } 
    ui.tableView_2->show();
}

void QPLTMLista::deleteDok(int idDok)
{
    QSqlQuery query;
    query.clear();
    query.prepare(
        "delete from magacin_prodavnica where dok_tip = 20 and dok_id = :a"
        );
    query.bindValue(":a", idDok);	
    query.exec();
}
void QPLTMLista::on_pushButton_clicked()
{
    emit procF2();
}
void QPLTMLista::on_pushButton_2_clicked()
{
    emit procF3();
}

QStringList QPLTMLista::geInfo()
{
    QStringList info;
    info.clear();
    info << m_komintent_naziv << m_komintent_adresa << m_komintent_grad << m_fakturadatum << m_fakturaBr 
		<< ui.lineEdit->text()  // naziv prodavnica
		<< ui.lineEdit_2->text()  // naziv adresa
		<< ui.lineEdit_3->text()  // naziv grad
		<< ui.lineEdit_4->text()  // naziv edb
		<< ui.lineEdit_5->text() // naziv zirosmetka
		<< m_pltm_broj_print;
    return info;
}

void QPLTMLista::setInitText(QString text)
{
    ui.tableView->setFocus();
}

void QPLTMLista::lineEdit7Pressed(const QString & text)
{
    lista(text + "%");
}